package com.nhc.activity_fragment;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.PathEffect;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.astrob.NavFrameSDK;
import com.astrob.activitys.DMapActivity;
import com.astrob.activitys.PositionProvider;
import com.astrob.model.LonLat;
import com.astrob.model.Msg;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.astrob.view.Car;
import com.astrob.view.Compass;
import com.astrob.view.MapViewS;
import com.astrob.view.TrackShow;
import com.astrob.view.ZoomView;
import com.nhc.database.dbmodel.TrackPoint;
import com.nhc.database.dbmodel.WayPoint;
import com.nhc.database.dbmodel.WayTrail;
import com.nhc.database.manager.DBDataCenter;
import com.nhc.model.MapSetInfo;
import com.nhc.view.MultiMapView;

import org.mapsforge.core.graphics.Path;
import org.mapsforge.core.graphics.Style;
import org.mapsforge.core.model.LatLong;
import org.mapsforge.core.util.MercatorProjection;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.layer.Layer;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.util.BoundingBox;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.Projection;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.Polyline;
import org.osmdroid.views.overlay.simplefastpoint.LabelledGeoPoint;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import zuo.biao.library.base.BaseFragment;

public class NaviTrackMapFragment extends BaseFragment implements MapViewS.MapCallBack,
        PositionProvider.PosCallBack, View.OnClickListener {
    private final String TAG = "NaviTrackMapFragment";

    //与Activity通信<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 创建一个Fragment实例
     *
     * @return
     */
    public static NaviTrackMapFragment createInstance() {
        return new NaviTrackMapFragment();
    }
    //与Activity通信>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    private WayTrail wayTrailEdit = null;
    private boolean isWayTrailThis = false;//是否为当前航迹

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        setContentView(R.layout.navitrackmap_fragment);

        wayTrailEdit = DBDataCenter.getInstance().wayTrailEdit;

        if (DBDataCenter.getInstance().wayTrailThis != null
                && wayTrailEdit.getId() == DBDataCenter.getInstance().wayTrailThis.getId()) {
            isWayTrailThis = true;
        }

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

        return view;//返回值必须为view
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    Car mCar = new Car();
    Compass mCompass = new Compass();
    MultiMapView mMultiMapView;
    ZoomView mZoom;
    TextView mScale;
    Button btn_navitrackmap_backnavi;
    Button btn_navitrackmap_detail;
    TextView tv_navitrackmap_lenth;
    TextView tv_navitrackmap_name;
    Button btn_navitrackmap_pre;
    Button btn_navitrackmap_next;

    @Override
    public void initView() {//必须在onCreateView方法内调用
        mMultiMapView = (MultiMapView) findViewById(R.id.id_multimap);
        mMultiMapView.setMapsource(SysUtils.getInstance().mapsource);
        initMapEngin();
        mZoom = (ZoomView) findViewById(R.id.id_zoomview);
        mScale = (TextView) findViewById(R.id.id_map_scalebar);
        btn_navitrackmap_backnavi = (Button) findViewById(R.id.btn_navitrackmap_backnavi);
        btn_navitrackmap_detail = (Button) findViewById(R.id.btn_navitrackmap_detail);
        tv_navitrackmap_name = (TextView) findViewById(R.id.tv_navitrackmap_name);
        tv_navitrackmap_lenth = (TextView) findViewById(R.id.tv_navitrackmap_lenth);

        btn_navitrackmap_pre = (Button) findViewById(R.id.btn_navitrackmap_pre);
        btn_navitrackmap_next = (Button) findViewById(R.id.btn_navitrackmap_next);

        if (isWayTrailThis) {
            tv_navitrackmap_name.setText(R.string.dqhj);
            btn_navitrackmap_backnavi.setText(R.string.hjfc);
        } else {
            tv_navitrackmap_name.setText(wayTrailEdit.getName());
        }

        if (SysUtils.getInstance().mapsource == 1000 || SysUtils.getInstance().mapsource == 1001) {
            mScale.setVisibility(View.VISIBLE);
        } else {
            mScale.setVisibility(View.GONE);
        }
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initData() {//必须在onCreateView方法内调用
        mCompass.setLeftTop(3, 50);

        String DIS[] = SysUtils.getInstance().getDistanceStr((int) wayTrailEdit.getTrail_distance());
        tv_navitrackmap_lenth.setText(getString(R.string.jl) + ": " + DIS[0] + DIS[1]);
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreateView方法内调用
        mMultiMapView.setScale(200000);
        mZoom.setOnClickListener(this);
        mMultiMapView.mMapViewS.setNeedPopTipInfo(false);
        btn_navitrackmap_backnavi.setOnClickListener(this);
        btn_navitrackmap_detail.setOnClickListener(this);

        findViewById(R.id.btnlocal).setOnClickListener(this);
        btn_navitrackmap_pre.setOnClickListener(this);
        btn_navitrackmap_next.setOnClickListener(this);

        ArrayList<TrackPoint> trackPointList = DBDataCenter.getInstance().getTrackPointByWayTrail(wayTrailEdit, null);
        mMultiMapView.setScale(100000);
        mMultiMapView.setMapOrientation(0);

//        onLocal();
        initWayTrailpoints();

        if (trackPointList.size() > 0) {
            showFullTrack();
        }

    }

    List<GeoPoint> _points = new ArrayList<>();
    Paint _paint;//forWayTrail

    //activity内不支持地图切换，如果切换就要保存火星坐标的点和正常GPS点
    void initWayTrailpoints() {
        _points.clear();
        for (int i = 0; i < wayTrailEdit.trackPointList.size(); i++) {
            TrackPoint tp = wayTrailEdit.trackPointList.get(i);
            LonLat poiLL = tp.getLL();
            _points.add(new GeoPoint(poiLL.GetLat(), poiLL.GetLon()));
        }

        if (_paint == null) {
            _paint = new Paint();
            _paint.reset();
            _paint.setStyle(Paint.Style.STROKE);
            _paint.setStrokeWidth(8);
            _paint.setStrokeJoin(Paint.Join.ROUND);
            _paint.setAntiAlias(true);
        }

    }

    public void showFullTrack() {
        ArrayList<TrackPoint> trackPointList = DBDataCenter.getInstance().getTrackPointByWayTrail(wayTrailEdit, null);
        mMultiMapView.setScale(100000);
        mMultiMapView.setMapOrientation(0);

        int size = trackPointList.size();
        if (size == 1) {
            LonLat ll = trackPointList.get(0).getLL();
            mMultiMapView.setMapCenter(ll);
            return;
        }

        double MinLon = 10000;
        double MinLat = 10000;
        double MaxLon = -1000;
        double MaxLat = -1000;

        for (int i = 0; i < size; i++) {
            if (trackPointList.get(i).getLL().GetLon() < MinLon) {
                MinLon = trackPointList.get(i).getLL().GetLon();
            }

            if (trackPointList.get(i).getLL().GetLat() < MinLat) {
                MinLat = trackPointList.get(i).getLL().GetLat();
            }

            if (trackPointList.get(i).getLL().GetLon() > MaxLon) {
                MaxLon = trackPointList.get(i).getLL().GetLon();
            }

            if (trackPointList.get(i).getLL().GetLat() > MaxLat) {
                MaxLat = trackPointList.get(i).getLL().GetLat();
            }
        }

        LonLat pos = new LonLat((MinLon + MaxLon) / 2, (MinLat + MaxLat) / 2);
        mMultiMapView.setMapCenter(pos);
        LonLat posA = new LonLat(MinLon, MinLat);
        LonLat posB = new LonLat(MaxLon, MaxLat);
        double distance = Start.getInstance().MapKit().getDistance(posA, posB);

        if (distance < 500) {
            Start.getInstance().MapKit().setScale(100000);
        } else if (distance < 1000) {
            Start.getInstance().MapKit().setScale(50000);
        } else if (distance < 2000) {
            Start.getInstance().MapKit().setScale(25000);
        } else if (distance < 4000) {
            Start.getInstance().MapKit().setScale(10000);
        } else if (distance < 8000) {
            Start.getInstance().MapKit().setScale(5000);
        } else if (distance < 16000) {
            Start.getInstance().MapKit().setScale(2500);
        } else if (distance < 32000) {
            Start.getInstance().MapKit().setScale(1000);
        } else if (distance < 64000) {
            Start.getInstance().MapKit().setScale(500);
        } else if (distance < 128000) {
            Start.getInstance().MapKit().setScale(250);
        } else if (distance < 256000) {
            Start.getInstance().MapKit().setScale(125);
        } else {
            Start.getInstance().MapKit().setScale(50);
        }

        mMultiMapView.setScale(Start.getInstance().MapKit().getScale());
        //
        if (distance < 500) {
            mMultiMapView.mMapViewOnline.getController().setZoom(16);
        } else if (distance < 1000) {
            mMultiMapView.mMapViewOnline.getController().setZoom(15);
        } else if (distance < 2000) {
            mMultiMapView.mMapViewOnline.getController().setZoom(14);
        } else if (distance < 4000) {
            mMultiMapView.mMapViewOnline.getController().setZoom(13);
        } else if (distance < 8000) {
            mMultiMapView.mMapViewOnline.getController().setZoom(12);
        } else if (distance < 16000) {
            mMultiMapView.mMapViewOnline.getController().setZoom(11);
        } else if (distance < 32000) {
            mMultiMapView.mMapViewOnline.getController().setZoom(10);
        } else if (distance < 64000) {
            mMultiMapView.mMapViewOnline.getController().setZoom(9);
        } else if (distance < 128000) {
            mMultiMapView.mMapViewOnline.getController().setZoom(8);
        } else if (distance < 256000) {
            mMultiMapView.mMapViewOnline.getController().setZoom(7);
        } else {
            mMultiMapView.mMapViewOnline.getController().setZoom(6);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        PositionProvider.getInstance().mCallback = this;
        if (_paint != null) {
            _paint.setColor(wayTrailEdit.getColor());
            int pathstyle = wayTrailEdit.getPathstyle();
            PathEffect pathEffect = TrackShow.getInstance().getPathEffect(pathstyle);
            _paint.setPathEffect(pathEffect);
        }
        mMultiMapView.updateMap();
    }

    @Override
    public void onPause() {
        super.onPause();
        PositionProvider.getInstance().mCallback = null;
    }

    public Handler getHandler() {
        return mHandler;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case Msg.UPDATEPOS:
                    break;
                case Msg.SHOWTIP:
                    break;
                case Msg.UPDATEMAP:
//					updateMapView();
                    break;
                case Msg.FINISHUPDATEMAP:
                    finishUpdatedMapView();
                    break;
                case Msg.MAPLEFT:
                    mMultiMapView.moveMap(-5, 0);
                    break;
                case Msg.MAPRIGHT:
                    mMultiMapView.moveMap(5, 0);
                    break;
                case Msg.MAPUP:
                    mMultiMapView.moveMap(0, -5);
                    break;
                case Msg.MAPDOWN:
                    mMultiMapView.moveMap(0, 5);
                    break;
                case Msg.MAPZOOMIN:
                    onZoomIn();
                    break;
                case Msg.MAPZOOMOUT:
                    onZoomOut();
                    break;
            }
        }
    };

    private void finishUpdatedMapView() {
        if (mMultiMapView.getMapsource() != 1000) {
            mZoom.updateState(0);
        } else {
            mZoom.updateState();
        }
        mScale.setText(mMultiMapView.getScaleString());

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnzoomin:
                onZoomIn();
                break;
            case R.id.btnzoomout:
                onZoomOut();
                break;
            case R.id.btn_navitrackmap_backnavi:
                onBackNavi();
                break;
            case R.id.btn_navitrackmap_detail:
                onDetail();
                break;
            case R.id.btnlocal:
                onLocal();
                break;
            case R.id.btn_navitrackmap_next:
                onShowNextTp();
                break;
            case R.id.btn_navitrackmap_pre:
                oonShowPreTp();
                break;
            default:
                break;
        }
    }

    int _tpIndex = 0;//航迹索引；

    private void oonShowPreTp() {
        _tpIndex -= 5;
        setMapCenter(_tpIndex);
    }

    private void onShowNextTp() {
        _tpIndex += 5;
        setMapCenter(_tpIndex);
    }

    private void setMapCenter(int indexTp) {
        if (wayTrailEdit.trackPointList == null
                || wayTrailEdit.trackPointList.size() < 1) {
            return;
        }

        if (_tpIndex < 0) {
            _tpIndex = 0;
        }
        if (_tpIndex >= wayTrailEdit.trackPointList.size()) {
            _tpIndex = wayTrailEdit.trackPointList.size() - 1;
        }
        setMapCenter(wayTrailEdit.trackPointList.get(_tpIndex).getLL());

        if (_tpIndex == 0) {
            btn_navitrackmap_pre.setEnabled(false);
            btn_navitrackmap_next.setEnabled(true);
        } else if (_tpIndex == wayTrailEdit.trackPointList.size() - 1) {
            btn_navitrackmap_pre.setEnabled(true);
            btn_navitrackmap_next.setEnabled(false);
        } else {
            btn_navitrackmap_pre.setEnabled(true);
            btn_navitrackmap_next.setEnabled(true);
        }

    }

    void onLocal() {
        if (Utils.isFastDoubleClick())
            return;
        _tpIndex = 0;
        setMapCenter(_tpIndex);
    }

    void setMapCenter(LonLat ll) {
        if (ll == null) {
            return;
        }
        mMultiMapView.setMapCenter(ll);
        mMultiMapView.setScale(100000);
        mMultiMapView.updateMap();
    }

    private void onDetail() {
        if (Utils.isFastDoubleClick())
            return;
        showShortToast("onDetail");
    }

    Handler mFHandler = null;// for 双击全屏显示

    public void setFatherHandler(Handler fHandler) {
        mFHandler = fHandler;
    }

    private void onBackNavi() {
        if (Utils.isFastDoubleClick())
            return;

        if (wayTrailEdit.trackPointList.size() < 3) {
            showShortToast(getString(R.string.navitrackmap_navi));
            return;
        }

        if (mFHandler != null) {
            if (!isWayTrailThis) {
                mFHandler.sendEmptyMessage(Msg.NAVITRACK_NAVI);
            } else {
                mFHandler.sendEmptyMessage(Msg.NAVITRACK_NAVIBACK);
            }
        }
    }

    void onZoomIn() {
        mMultiMapView.zoomIn();
        mMultiMapView.updateMap();
    }

    void onZoomOut() {
        mMultiMapView.zoomOut();
        mMultiMapView.updateMap();
    }


    @Override
    public void updatePos(NavFrameSDK.NavPosition navpos, boolean isNetPos) {
        mHandler.sendEmptyMessage(Msg.UPDATEPOS);
    }

    @Override
    public void drawOverlay(Canvas canvas, float ws) {

        if (mMultiMapView.getMapsource() != 1000) {
            return;
        }

        MapSetInfo.getInstance().draw(context, canvas, ws, mMultiMapView.mMapViewS);

//        mCar.draw(getContext(), canvas, ws, ws);
        mCompass.draw(getContext(), canvas, ws, ws);

        drawMarker(canvas, ws);//显示航点
        TrackShow.getInstance().drawWayTrailAll(context, canvas, ws, mMultiMapView.mMapViewS, wayTrailEdit);
//        TrackShow.getInstance().drawWayTrailByPoints(context, canvas, ws, mMultiMapView.mMapViewS, _points, _paint, true);
        //画完图
        mHandler.sendEmptyMessage(Msg.FINISHUPDATEMAP);
    }

    private void drawMarker(Canvas canvas, float ws) {
        ArrayList<WayPoint> waypointList = DBDataCenter.getInstance().getWaypointList();
        int count = waypointList.size();
        int resId;
        for (int i = 0; i < count; ++i) {
            WayPoint wp = waypointList.get(i);
            LonLat poiLL = wp.getLL();
            if (mMultiMapView.isgcj02) {
                poiLL = wp.getLL_gcj();
            }
            if (!mMultiMapView.mMapViewS.isInMapRegion(poiLL)) {
                continue;
            }
            resId = wp.getTypeIcon();
            Bitmap bm = ((BitmapDrawable) getResources().getDrawable(resId))
                    .getBitmap();
            Point e = Start.getInstance().MapKit().LL2XY(poiLL);
            int x = (int) (e.x * ws - bm.getWidth() / 2);
            int y = (int) (e.y * ws - bm.getHeight() / 2);
            canvas.drawBitmap(bm, x, y, null);

            if (Start.getInstance().MapKit().getScale() > 10000) {
                Paint paint = new Paint();
                paint.reset();
                if (wp.getType() == 1) {
                    paint.setColor(Color.RED);//警告点
                } else {
                    paint.setColor(Color.BLUE);
                }

                int lp = 32;
                paint.setTextSize(13);
                if (SysUtils.getInstance().is240x320) {
                    paint.setTextSize(11);
                    lp = 16;
                }
                paint.setFakeBoldText(true);
                paint.setAntiAlias(true);
                paint.setAlpha(220);
                paint.setUnderlineText(true);
//              paint.measureText(wp.getName());
                String name = wp.getName();
                if (name.length() > 13) {
                    name = wp.getName().substring(0, 13);
                }
                canvas.drawText(name, x + bm.getWidth() - 2, y + lp, paint);
            }

        }
    }

    @Override
    public void onDestroy() {
        mMultiMapView.destroyMap();
        super.onDestroy();
    }

    @Override
    public void popTipInfo(NavFrameSDK.POIDescription data) {

    }

    @Override
    public void moveMap(boolean removeTip) {

    }

    @Override
    public void touchUp() {

    }

    @Override
    public void longPress(LonLat ll) {

    }

    @Override
    public void doubleClick(LonLat ll) {

    }

    @Override
    public void singleClick(LonLat ll, Point tipPoint) {

    }

    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //====================
    private void initMapEngin() {

        if (mMultiMapView.getMapsource() == 1001) {
            mapsforgeLayer = new MapsforgeLayer();
            mMultiMapView.mapView.addLayer(mapsforgeLayer);
        } else if (mMultiMapView.getMapsource() != 1000) {
            mGisOverlay = new CustomPointOverlay();
            mMultiMapView.mMapViewOnline.getOverlays().add(mGisOverlay);
        }

        mMultiMapView.setMapCallback(this, mapListener);
    }

    //======OSM
    MapListener mapListener = new MapListener() {
        @Override
        public boolean onScroll(ScrollEvent scrollEvent) {

            return true;
        }

        @Override
        public boolean onZoom(ZoomEvent zoomEvent) {
            return false;
        }

        @Override
        public void longPress(Point pt) {
            if (pt == null) {
                return;
            }
        }

        //双击
        @Override
        public void doubleClick(Point pt) {
            if (pt == null) {
                return;
            }
        }

        //单击 单击后
        @Override
        public void singleClick(Point pt) {
            if (pt == null) {
                return;
            }
        }

        //移图后抬起
        @Override
        public void touchUp() {
        }

        //手指移动-切换到移图模式
        @Override
        public void moveMap() {
        }

    };

    private CustomPointOverlay mGisOverlay = null;

    public class CustomPointOverlay extends Overlay {

        private final Point mMapCoordsProjected = new Point();

        Polyline _routeline = null;

        public CustomPointOverlay() {
        }

        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {

            if (mMultiMapView.getMapsource() >= 1000 && mMultiMapView.getMapsource() <= 1001) {
                return;
            }

            MapSetInfo.getInstance().draw2(getContext(), canvas, mapView);
            mCompass.draw2(getContext(), canvas, (int) mapView.getMapOrientation());

            drawMarker2(canvas);//显示航点

//            TrackShow.getInstance().drawWayTrail2(getContext(), canvas, 1, mapView, wayTrailEdit, mMultiMapView.isgcj02);//ok
            TrackShow.getInstance().drawWayTrail2(getContext(), canvas, mapView, wayTrailEdit, mMultiMapView.isgcj02);//ok
//            if (_routeline == null) {
//                _routeline = new Polyline();
//                _routeline.setWidth(8);
//                _routeline.setPoints(_points);
//            }
//
//            int size = _points.size();
//            if (size > 1) {
//                _routeline.setColor(wayTrailEdit.getColor());
//                int pathstyle = wayTrailEdit.getPathstyle();
//                PathEffect pathEffect = TrackShow.getInstance().getPathEffect(pathstyle);
//                _routeline.getPaint().setPathEffect(pathEffect);
//                _routeline.draw(canvas, mapView, shadow);
//
//                Point ff0 = LL2XY(new LonLat(_points.get(0).getLongitude(), _points.get(0).getLatitude()));
//                Point ffE = LL2XY(new LonLat(_points.get(size-1).getLongitude(), _points.get(size-1).getLatitude()));
//                if (ff0 != null) {
//                    Bitmap bmS = ((BitmapDrawable) context.getResources().getDrawable(
//                            R.drawable.map_marker3)).getBitmap();
//
//                    int x = (int) (ff0.x - bmS.getWidth() / 2);
//                    int y = (int) (ff0.y - bmS.getHeight());
//                    canvas.drawBitmap(bmS, x, y, null);
//                }
//
//                if (ffE != null) {
//                    Bitmap bmD = ((BitmapDrawable) context.getResources().getDrawable(
//                            R.drawable.map_marker2)).getBitmap();
//
//                    int x = (int) (ffE.x  - bmD.getWidth() / 2);
//                    int y = (int) (ffE.y  - bmD.getHeight());
//                    canvas.drawBitmap(bmD, x, y, null);
//                }
//            }

            //画完图
            mHandler.sendEmptyMessage(Msg.FINISHUPDATEMAP);


        }

        //经纬度坐标到屏幕坐标的转换
        Point LL2XY(LonLat ll) {
            Point B = new Point();
            mMultiMapView.mMapViewOnline.getProjection().toProjectedPixels(ll.GetLat(),
                    ll.GetLon(), mMapCoordsProjected);
            Projection pj = mMultiMapView.mMapViewOnline.getProjection();
            pj.toPixelsFromProjected(mMapCoordsProjected, B);
            return B;
        }

        void drawMarker2(Canvas canvas) {

            BoundingBox bb = mMultiMapView.mMapViewOnline.getBoundingBox();//获取当前区域
            //double[] regions = {_maxLon, _maxLat, _minLon, _minLat};
            double[] regions = {bb.getLonEast(), bb.getLatNorth(), bb.getLonWest(), bb.getLatSouth()};


            ArrayList<WayPoint> waypointList = DBDataCenter.getInstance().getWaypointList();
            int count = waypointList.size();
            int resId;
            for (int i = 0; i < count; ++i) {
                WayPoint wp = waypointList.get(i);
                LonLat poiLL = wp.getLL();
                if (mMultiMapView.isgcj02) {
                    poiLL = wp.getLL_gcj();
                }
                if (poiLL.GetLon() > regions[0] || poiLL.GetLat() > regions[1]
                        || poiLL.GetLon() < regions[2] || poiLL.GetLat() < regions[3]) {
                    continue;
                }
                resId = wp.getTypeIcon();
                Bitmap bm = ((BitmapDrawable) getResources().getDrawable(resId))
                        .getBitmap();
                Point e = LL2XY(poiLL);
                int x = (int) (e.x - bm.getWidth() / 2);
                int y = (int) (e.y - bm.getHeight() / 2);
                canvas.drawBitmap(bm, x, y, null);

                if (Start.getInstance().MapKit().getScale() > 10000) {
                    Paint paint = new Paint();
                    paint.reset();
                    if (wp.getType() == 1) {
                        paint.setColor(Color.RED);//警告点
                    } else {
                        paint.setColor(Color.BLUE);
                    }
                    int lp = 32;
                    paint.setTextSize(13);
                    if (SysUtils.getInstance().is240x320) {
                        paint.setTextSize(11);
                        lp = 16;
                    }
                    paint.setFakeBoldText(true);
                    paint.setAntiAlias(true);
                    paint.setAlpha(220);
                    paint.setUnderlineText(true);
//              paint.measureText(wp.getName());
                    String name = wp.getName();
                    if (name.length() > 12) {
                        name = wp.getName().substring(0, 12);
                    }
                    canvas.drawText(name, x + bm.getWidth() - 2, y + lp, paint);
                }

            }
        }

    }

    //======Mapsforge
    MapsforgeLayer mapsforgeLayer;

    public class MapsforgeLayer extends Layer {

        org.mapsforge.core.model.BoundingBox bb;
        byte zoomLevel;
        org.mapsforge.core.graphics.Canvas canvas;
        org.mapsforge.core.model.Point topLeftPoint;

        public MapsforgeLayer() {
        }

        @Override
        public synchronized void draw(org.mapsforge.core.model.BoundingBox bb, byte zoomLevel, org.mapsforge.core.graphics.Canvas canvas, org.mapsforge.core.model.Point topLeftPoint) {

            if (mMultiMapView.getMapsource() != 1001) {
                return;
            }

            this.bb = bb;
            this.zoomLevel = zoomLevel;
            this.canvas = canvas;
            this.topLeftPoint = topLeftPoint;

            MapSetInfo.getInstance().draw3(getContext(), canvas, bb, zoomLevel, topLeftPoint, displayModel);
            mCompass.draw3(getContext(), canvas, 0, bb, zoomLevel, topLeftPoint, displayModel);

            android.graphics.Canvas androidCanvas = AndroidGraphicFactory.getCanvas(canvas);
            drawMarker3(androidCanvas);//显示航点
            TrackShow.getInstance().drawWayTrail3(getContext(), androidCanvas, bb, zoomLevel, topLeftPoint, displayModel, wayTrailEdit);//ok

//            drawWayTrail(androidCanvas);
            //画完图
            mHandler.sendEmptyMessage(Msg.FINISHUPDATEMAP);

        }

        void drawWayTrail(Canvas canvas) {

            long mapSize = MercatorProjection.getMapSize(zoomLevel, displayModel.getTileSize());
            android.graphics.Path path = new android.graphics.Path();
            int size = _points.size();
            if (size > 1) {
                for (int i = 0; i < size; i++) {
                    GeoPoint pt = _points.get(i);
                    float x = (float) (MercatorProjection.longitudeToPixelX(pt.getLongitude(), mapSize) - topLeftPoint.x);
                    float y = (float) (MercatorProjection.latitudeToPixelY(pt.getLatitude(), mapSize) - topLeftPoint.y);
                    if (i == 0) {
                        path.moveTo(x, y);
                    } else {
                        path.lineTo(x, y);
                    }
                }
                canvas.drawPath(path, _paint);

                Point ff0 = LL2XY(new LonLat(_points.get(0).getLongitude(), _points.get(0).getLatitude()));
                Point ffE = LL2XY(new LonLat(_points.get(size-1).getLongitude(), _points.get(size-1).getLatitude()));
                if (ff0 != null) {
                    Bitmap bmS = ((BitmapDrawable) context.getResources().getDrawable(
                            R.drawable.map_marker3)).getBitmap();

                    int x = (int) (ff0.x - bmS.getWidth() / 2);
                    int y = (int) (ff0.y - bmS.getHeight());
                    canvas.drawBitmap(bmS, x, y, null);
                }

                if (ffE != null) {
                    Bitmap bmD = ((BitmapDrawable) context.getResources().getDrawable(
                            R.drawable.map_marker2)).getBitmap();

                    int x = (int) (ffE.x  - bmD.getWidth() / 2);
                    int y = (int) (ffE.y  - bmD.getHeight());
                    canvas.drawBitmap(bmD, x, y, null);
                }
            }
        }


        //经纬度坐标到屏幕坐标的转换
        Point LL2XY(LonLat ll) {
            long mapSize = MercatorProjection.getMapSize(zoomLevel, displayModel.getTileSize());
            int x = (int) (MercatorProjection.longitudeToPixelX(ll.GetLon(), mapSize) - topLeftPoint.x);
            int y = (int) (MercatorProjection.latitudeToPixelY(ll.GetLat(), mapSize) - topLeftPoint.y);
            Point B = new Point(x, y);
            return B;
        }

        void drawMarker3(Canvas canvas) {

            double[] regions = {bb.maxLongitude, bb.maxLatitude, bb.minLongitude, bb.minLatitude};

            ArrayList<WayPoint> waypointList = DBDataCenter.getInstance().getWaypointList();
            int count = waypointList.size();
            int resId;
            for (int i = 0; i < count; ++i) {
                WayPoint wp = waypointList.get(i);
                LonLat poiLL = wp.getLL();
                if (poiLL.GetLon() > regions[0] || poiLL.GetLat() > regions[1]
                        || poiLL.GetLon() < regions[2] || poiLL.GetLat() < regions[3]) {
                    continue;
                }
                resId = wp.getTypeIcon();
                Bitmap bm = ((BitmapDrawable) getResources().getDrawable(resId))
                        .getBitmap();
                Point e = LL2XY(poiLL);
                int x = (int) (e.x - bm.getWidth() / 2);
                int y = (int) (e.y - bm.getHeight() / 2);
                canvas.drawBitmap(bm, x, y, null);

                if (Start.getInstance().MapKit().getScale() > 10000) {
                    Paint paint = new Paint();
                    paint.reset();

                    if (wp.getType() == 1) {
                        paint.setColor(Color.RED);//警告点
                    } else {
                        paint.setColor(Color.BLUE);
                    }
                    int lp = 32;
                    paint.setTextSize(13);
                    if (SysUtils.getInstance().is240x320) {
                        paint.setTextSize(11);
                        lp = 16;
                    }

                    String name = wp.getName();
                    if (name.length() > 12) {
                        name = wp.getName().substring(0, 12);
                    }
                    canvas.drawText(name, x + bm.getWidth() - 2, y + lp, paint);
                }
            }
        }

    }


}